var TableEditable = function () {

    return {

        
        init: function () {
			
            function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
				oTable.fnUpdate(aData['authIco'], nRow,0, false);
				oTable.fnUpdate(aData['authName'], nRow,1, false);
				oTable.fnUpdate(aData['parentId'], nRow,2, false);
				oTable.fnUpdate(aData['controller'], nRow,3, false);
				oTable.fnUpdate(aData['action'], nRow,4, false);
				oTable.fnUpdate(aData['isShow'], nRow,5, false);
				oTable.fnUpdate('<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>', nRow, 6, false);
                oTable.fnDraw();
            }

            function editRow(oTable, nRow,isNew) {
				var isNew=isNew?isNew:'';
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
                jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['authIco'] + '">';
                jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['authName'] + '">';
                //jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['parentId'] + '">';
				
                jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['controller'] + '">';
				jqTds[4].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['action'] + '">';
				jqTds[5].innerHTML = '<input type="text" class="form-control input-small" value="' + aData['isShow'] + '">';
                jqTds[6].innerHTML = '<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" '+isNew+' href=""><i class="fa fa-times"></i> 取消</a>';
				$.ajax({
						url: Url,
						type: 'POST',
						dataType: 'json',
						//data: aData,
						success : function(data) {
							var parentId = '<select class="sidebar-pos-option form-control input-small">';
							for (var i = 0, iLen = data.length; i < iLen; i++) {
								if(aData['parentId']==data[i].authId){
									parentId +='<option value="'+data[i].authId+'" selected="selected">'+ data[i].authName+'</option>';
								}else{
									parentId +='<option value="'+data[i].authId+'">'+ data[i].authName+'</option>';
								}
							}
								parentId +='</select>';
							jqTds[2].innerHTML = parentId;
						}
					});
			
			
			
			}

            function saveRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
                oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
                oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
                oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
				oTable.fnUpdate(jqInputs[4].value, nRow, 4, false);
				oTable.fnUpdate(jqInputs[5].value, nRow, 5, false);
                oTable.fnUpdate('<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>', nRow, 6, false);
                oTable.fnDraw();
            }
            var oTable = $('#sample_editable_1').dataTable({
                "aLengthMenu": [
                    [-1,5, 15, 20],
                    ["全部",'5条', '15条', '20条'] 
                ],
                "iDisplayLength": -1,
				"aaSorting":[[6,'desc']],
                "sPaginationType": "bootstrap",
				"bStateSave": true, 
                "oLanguage": {
					"sSearch":"搜索",
                    "sLengthMenu": "每页显示 _MENU_ 记录",    
					"sEmptyTable":"没有数据",
					"sInfo": "当前数据为从第 _START_ 到第 _END_ 条数据；总共有 _TOTAL_ 条记录",   
					"sInfoEmpty": "没有数据",   
					"sInfoFiltered" : "",
					"sInfoPostFix" : "",
					"sLoadingRecords":"",
					"sProcessing": "正在加载数据...", 
					"sZeroRecords": "没有检索到数据", 
                    "oPaginate": {   
						"sFirst": "首页",   
						"sPrevious": "上一页",   
						"sNext": "下一页",   
						"sLast": "尾页"  
					}   
                },
				"sAjaxSource":remoteUrl,
				"sAjaxDataProp": "data",
				"aoColumns": [
					{"sTitle":'图标',"mDataProp": 'authIco'},
					{"sTitle":'名称',"mDataProp": 'authName'},
					{"sTitle":'父级',"mDataProp": 'parentId'},
					{"sTitle":'控制器',"mDataProp": 'controller'},
					{"sTitle":'操作器',"mDataProp": 'action'},
					{"sTitle":'是否边栏显示',"mDataProp": 'isShow'},
					{"sTitle":'操作',"mDataProp": 'ac'}
				],
                "aoColumnDefs": [{
                        'bSortable': false,
						'aTargets': ['_all']
                    },
					
					{"aTargets":[0],"mRender":function(data,type,full){
                     return '<span class="row-details row-details-close" id="show'+full['authId']+'"></span><i class="fa '+data+'"></i>';
                    },"sClass":'text-center',"sWidth":'5%'},
					{"aTargets":[1],"mRender":function(data,type,full){
						if(full['parentId']>0){
							return ' ├─── '+data+'<i id="show'+full['parentId']+'"></i>';
						}else{
							return data;
						}
                    }},
					{"aTargets":[5],"mRender":function(data,type,full){
						if(data==1){
							return '<a href="#" class="btn btn-xs blue">显示</a>';
						}else{
							return '<a href="#" class="btn btn-xs default">隐藏</a>';
						}
                    },"sClass":'text-center',"sWidth":'5%'},
					{"aTargets":[6],"mRender":function(data,type,full){
                     return '<a class="edit btn btn-xs default" href=""><i class="fa fa-edit"></i> 修改</a></a><a class="delete btn btn-xs red" href=""><i class="fa fa-trash-o"></i> 删除</a>';
                    },"sClass":'text-center',"sWidth":'5%'}
                ]
            });

            jQuery('#sample_editable_1_wrapper .dataTables_filter input').addClass("form-control input-medium input-inline"); // modify table search input
            jQuery('#sample_editable_1_wrapper .dataTables_length select').addClass("form-control input-small"); // modify table per page dropdown
            jQuery('#sample_editable_1_wrapper .dataTables_length select').select2({
                showSearchInput : false 
            }); 
			
			
            var nEditing = null;

			$('#sample_editable_1').on('click', ' tbody td .row-details', function () {
				var nTr = $(this).parents('tr')[0];
				var showId=$(this).attr('id');
				$('#sample_editable_1 tr').has('i[id^="show"]').slideUp();
				//alert(showId);exit;
				nnTr=$('#sample_editable_1 tr').has('i#'+showId);
				 if ( $(this).hasClass('row-details-open') )
				{
					/* This row is already open - close it */
					$(this).addClass("row-details-close").removeClass("row-details-open");
					nnTr.slideUp('3000');
					
				}
				else
				{
					/* Open this row */                
					$(this).addClass("row-details-open").removeClass("row-details-close");
					nnTr.slideDown('3000');
					
				} 
				
			});
			
            $('#sample_editable_1_new').click(function (e) {
                e.preventDefault();
				if (nEditing !== null) {
                    layer.confirm('确定不保存数据添加新行？',function(index){
						if($(nEditing).find("a[data-mode='new']").length>0){	
							oTable.fnDeleteRow(nEditing);	
						}else{
							restoreRow(oTable, nEditing);
						}
						var aiNew = oTable.fnAddData({"authIco":'', "authName":'', "parentId":'', "controller":'',"action":'',"isShow":'',
							"ac":'<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" data-mode="new" href=""><i class="fa fa-times"></i> 取消</a>'					
						});
						var nRow = oTable.fnGetNodes(aiNew[0]);
						editRow(oTable, nRow,"data-mode='new'");
						nEditing = nRow;
						layer.close(index);
					});
                }else{
					var aiNew = oTable.fnAddData({"authIco":'', "authName":'', "parentId":'', "controller":'',"action":'',"isShow":'',
						"ac":'<a class="edit btn btn-xs green" href="" name="Save"><i class="fa fa-check"></i> 保存</a></a><a class="cancel btn btn-xs default" data-mode="new" href=""><i class="fa fa-times"></i> 取消</a>'					
					});
					var nRow = oTable.fnGetNodes(aiNew[0]);
					editRow(oTable, nRow,"data-mode='new'");
					nEditing = nRow;
				}
				
				
				
				
                
            });

            $('#sample_editable_1 a.delete').live('click', function (e) {
                e.preventDefault();

                if (confirm("Are you sure to delete this row ?") == false) {
                    return;
                }

                var nRow = $(this).parents('tr')[0];
                oTable.fnDeleteRow(nRow);
                alert("Deleted! Do not forget to do some ajax to sync with backend :)");
            });

            $('#sample_editable_1 a.cancel').live('click', function (e) {
                e.preventDefault();
				var nRow = $(this).parents('tr')[0];
                if ($(this).attr("data-mode") == "new") {
                    
                    oTable.fnDeleteRow(nRow);
                } else {
                    restoreRow(oTable, nRow);
                    //nEditing = null;
                }
				nEditing = null;
            });

            $('#sample_editable_1 a.edit').live('click', function (e) {
                e.preventDefault();
                var nRow = $(this).parents('tr')[0];
                if (nEditing !== null && nEditing != nRow) {
                    layer.confirm('确定不保存数据编辑新行？',function(index){
						if($(nEditing).find("a[data-mode='new']").length>0){	
							oTable.fnDeleteRow(nEditing);	
						}else{
							restoreRow(oTable, nEditing);
						}
						editRow(oTable, nRow);
						nEditing = nRow;
						layer.close(index);
					});
                } else if (nEditing == nRow && this.name == "Save") {
                    /* Editing this row and want to save it */
                    saveRow(oTable, nEditing);
					nEditing = null;
					var aData = oTable.fnGetData(nRow);
					//alert(aData);
					$.ajax({
						url: ajaxUrl,
						type: 'POST',
						dataType: 'json',
						data: aData,
						success : function(data) {
							alert(data);
						}
					});
                    
					
					
					
					
					
                    //alert("Updated! Do not forget to do some ajax to sync with backend :)"+oTable.authId);
                } else {
                    /* No edit in progress - let's start one */
                    editRow(oTable, nRow);
                    nEditing = nRow;
                }
            });
        }

    };

}();